<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import {
  deleteAdminDataApi,
  updateAdminDataApi,
  disableAccountApi,
  enableAccountApi,
  getAdminDataApi,
  addAdminDataApi
} from "@/api/admin"
import { getDepartmentIdAndNameList } from "@/api/department"
import { type IGetAdminData, IAddAdminRequestData } from "@/api/admin/types/admin"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox, ElTree } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight, MoreFilled } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { IGetDepartmentData } from "@/api/department/types/department"
import { useUserStore } from "@/store/modules/user"
import { IUserInfoData } from "@/api/login/types/login"
import { getCheckedKeys, getExpandedKeys, hasAnthority, showPromptMessage } from "@/utils"
import { getOneAuthorityDataApi, updateGrantDataApi } from "@/api/authority"
import { resetAdminPassword } from "@/api/common"
import { IGetAuthorityResponseData, IUpdateGrantRequestData } from "@/api/authority/types/authority"
import { sendMsgApi } from "@/api/message/index"

defineOptions({
  name: "ElementPlus"
})
const userStore = useUserStore()
const userInfo = userStore.userInfo as IUserInfoData
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const addDialogVisible = ref<boolean>(false)
const addFormRef = ref<FormInstance | null>(null)
const loading = ref(false)
const addFormData = reactive<IAddAdminRequestData>({
  name: "",
  username: "",
  departmentId: undefined,
  sex: "",
  personalPhone: "",
  officialPhone: "",
  level: 1
})

const addFormRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入管理员姓名" }],
  username: [{ required: true, trigger: "blur", message: "请输入管理员" }],
  sex: [{ required: true, trigger: "blur", message: "请输入管理员账号" }],
  departmentId: [{ required: true, trigger: "blur", message: "请选择办学单位" }]
})
const handleCreate = () => {
  addFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      addFormData.departmentId = addFormData.level === 1 ? undefined : addFormData.departmentId
      if (currentUpdateId.value === undefined) {
        addAdminDataApi(addFormData).then(() => {
          ElMessage.success("新增成功")
          addDialogVisible.value = false
          getAdminData()
        })
      } else {
        updateAdminDataApi({
          id: currentUpdateId.value,
          ...addFormData
        }).then(() => {
          ElMessage.success("修改成功")
          addDialogVisible.value = false
          getAdminData()
        })
      }
    } else {
      return false
    }
  })
}
const resetForm = () => {
  currentUpdateId.value = undefined
  // addFormRef.value?.resetFields()
  addFormData.departmentId = undefined
  addFormData.name = ""
  addFormData.officialPhone = ""
  addFormData.personalPhone = ""
  addFormData.sex = ""
  addFormData.username = ""
}
//#endregion

//#region 删
const handleRowContentMenu = (row: IGetAdminData, column: any, event: Event) => {
  event.preventDefault()
}
const handleDelete = (row: IGetAdminData) => {
  ElMessageBox.confirm(`正在删除管理员：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteAdminDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getAdminData()
    })
  })
}
//#endregion

//#region 分配权限
const updateAuthData = ref<IUpdateGrantRequestData>({
  adminId: undefined,
  authorityIds: []
})
const treeRef = ref<InstanceType<typeof ElTree>>()
const defaultCheckedKeys = ref<number[]>([])
const expandedKeys = ref<number[]>([])
const treeDialogVisible = ref(false)
const AuthorityData = ref<IGetAuthorityResponseData[]>([])
const props = {
  label: "tag",
  children: "children"
}

const handleAllocation = (row: IGetAdminData) => {
  updateAuthData.value.adminId = row.id
  //获取权限
  getAuthoruty()
}

const resetPassword = (row: IGetAdminData) => {
  ElMessageBox.confirm(`正在重置管理员：${row.name}的密码，确认重置？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    loading.value = true
    resetAdminPassword(row.username)
      .then(() => {
        showPromptMessage("success", "操作成功")
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const handleCheckChange = () => {
  updateAuthData.value.authorityIds = treeRef.value!.getCheckedKeys(true) as number[]
}

const getAuthoruty = () => {
  updateAuthData.value.adminId &&
    getOneAuthorityDataApi(updateAuthData.value.adminId).then((res) => {
      AuthorityData.value = res.data.list
      defaultCheckedKeys.value = getCheckedKeys(res.data.list)
      expandedKeys.value = getExpandedKeys(res.data.list)
      treeDialogVisible.value = true
    })
}

const handleConfirmTree = () => {
  loading.value = true
  updateGrantDataApi(updateAuthData.value)
    .then(() => {
      showPromptMessage("success", "更新成功")
      treeDialogVisible.value = false
    })
    .finally(() => {
      loading.value = false
    })
}

const sendFormRef = ref<FormInstance | null>(null)
const sending = ref(false)
const sendData = ref<any>({})
const sendParams = ref({
  senderId: userInfo.id,
  content: "",
  priority: 0,
  recipientId: ""
})
const options = [
  {
    value: 0,
    label: "一般消息"
  },
  {
    value: 1,
    label: "重要消息"
  }
]
const sendMsg = (row: IGetAdminData) => {
  sending.value = true
  sendData.value = row
}

const confirmSendMsg = () => {
  loading.value = true
  sendParams.value.recipientId = sendData.value.id
  sendMsgApi(sendParams.value)
    .then(() => {
      ElMessage.success("发送成功")
      sending.value = false
    })
    .finally(() => {
      loading.value = false
    })
}

//#endregion

//#region 改
const sexOpions = [
  {
    label: "男",
    value: "男"
  },
  {
    label: "女",
    value: "女"
  }
]
const currentUpdateId = ref<undefined | number>(undefined)
const handleUpdate = (row: IGetAdminData) => {
  console.log(row)
  currentUpdateId.value = row.id
  addFormData.name = row.name
  addFormData.username = row.username
  addFormData.officialPhone = row.officialPhone
  addFormData.personalPhone = row.personalPhone
  addFormData.sex = row.sex
  addFormData.level = row.authority === "1" ? 2 : 1
  addFormData.departmentId = addFormData.level === 1 ? undefined : row.departmentId
  addDialogVisible.value = true
}
//#endregion

//#region 查
const AdminData = ref<IGetAdminData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const DepartmentData = ref<IGetDepartmentData[]>([])
const searchAdminData = reactive<{ name: string; departmentId: number | undefined }>({
  name: "",
  departmentId: undefined
})
//#获取部门
const getDepartment = async () => {
  const result = await getDepartmentIdAndNameList({ name: "", departmentId: userInfo.departmentId })
  DepartmentData.value = result.data.list
}
getDepartment()
const refreshing = ref(false)
const getAdminData = async () => {
  if (refreshing.value) return
  loading.value = true
  refreshing.value = true
  getAdminDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    departmentId: searchAdminData.departmentId || 0,
    name: searchAdminData.name
  })
    .then((res) => {
      paginationData.total = res.data.total
      AdminData.value = res.data.list
    })
    .catch(() => {
      AdminData.value = []
    })
    .finally(() => {
      refreshing.value = false
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getAdminData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchAdminData.name = ""
  searchAdminData.departmentId = undefined
  if (paginationData.currentPage === 1) {
    getAdminData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getAdminData()
}
//#endregion

const handleDisableAccount = (row: IGetAdminData) => {
  loading.value = true
  disableAccountApi(row.username)
    .then(() => {
      getAdminData()
      ElMessage.success("操作成功")
    })
    .finally(() => {
      loading.value = false
    })
}

const handleEnableAccount = (row: IGetAdminData) => {
  loading.value = true
  enableAccountApi(row.username)
    .then(() => {
      getAdminData()
      ElMessage.success("操作成功")
    })
    .finally(() => {
      loading.value = false
    })
}

const handleCommand = (command: string, row: IGetAdminData) => {
  switch (command) {
    case "reset":
      resetPassword(row)
      break
    case "allocation":
      handleAllocation(row)
      break
    case "ban":
      ElMessageBox.confirm(`是否确认封禁管理员：${row.name}？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        handleDisableAccount(row)
      })

      break
    case "unseal":
      ElMessageBox.confirm(`是否确认解封管理员：${row.name}？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        handleEnableAccount(row)
      })

      break
  }
}
/** 监听分页参数的变化 */
watch(
  [() => paginationData.currentPage, () => paginationData.pageSize, () => searchAdminData.departmentId],
  getAdminData,
  {
    immediate: true
  }
)
</script>

<template>
  <div class="app-container" v-loading="loading" element-loading-text="加载中">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchAdminData">
        <el-form-item prop="name" label="管理员名称">
          <el-input v-model="searchAdminData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-form inline>
        <el-form-item prop="department" label="办学单位">
          <el-select filterable v-model="searchAdminData.departmentId" placeholder="选择办学单位">
            <el-option v-for="item in DepartmentData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <div class="toolbar-wrapper">
        <div v-if="hasAnthority('admin.add')">
          <el-button type="primary" :icon="CirclePlus" @click="addDialogVisible = true">新增管理员</el-button>
        </div>
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="AdminData" @row-contextmenu="handleRowContentMenu">
          <el-table-column prop="name" label="管理员姓名" align="center" />
          <el-table-column prop="username" label="管理员账号" align="center" />
          <el-table-column prop="departmentName" label="所属机构" align="center" />
          <el-table-column
            prop="departmentId"
            label="账号类型"
            align="center"
            :formatter="(row) => (row.departmentId === 0 ? '一级' : '二级')"
          />
          <el-table-column prop="sex" label="性别" align="center" />
          <el-table-column prop="personalPhone" label="个人电话" align="center" />
          <el-table-column prop="officialPhone" label="办公电话" align="center" />
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template #default="scope">
              <div>
                <el-space>
                  <el-button
                    v-if="userInfo.authority === '1' || userInfo.authority === '2'"
                    type="warning"
                    link
                    size="small"
                    @click="sendMsg(scope.row)"
                    >发消息</el-button
                  >

                  <el-button
                    v-if="hasAnthority('admin.update')"
                    type="primary"
                    link
                    size="small"
                    @click="handleUpdate(scope.row)"
                    >修改</el-button
                  >
                  <el-button
                    v-if="hasAnthority('admin.delete')"
                    type="danger"
                    link
                    size="small"
                    @click="handleDelete(scope.row)"
                    >删除</el-button
                  >
                  <!--      v-if="hasAnthority('admin.grant')" -->

                  <el-dropdown trigger="click" @command="(command) => handleCommand(command, scope.row)">
                    <el-link type="info">
                      <el-icon>
                        <MoreFilled />
                      </el-icon>
                    </el-link>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="allocation">权限分配</el-dropdown-item>
                        <el-dropdown-item
                          command="reset"
                          v-if="scope.row.authority === '1' && userInfo.authority === '2'"
                          >重置密码</el-dropdown-item
                        >
                        <el-dropdown-item v-if="scope.row.able === 1" command="ban">封禁</el-dropdown-item>
                        <el-dropdown-item v-if="scope.row.able === 0" command="unseal">解封</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-space>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="currentUpdateId === undefined ? '新增管理员' : '修改管理员'"
      @close="resetForm"
      width="50%"
    >
      <el-form ref="addFormRef" :model="addFormData" :rules="addFormRules" label-width="110px" label-position="left">
        <el-form-item prop="level" label="管理员级别">
          <el-radio-group v-model="addFormData.level">
            <el-radio :label="1">一级</el-radio>
            <el-radio :label="2">二级</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="username" label="工号">
          <el-input v-model="addFormData.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="name" label="管理员姓名">
          <el-input v-model="addFormData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="sex" label="性别">
          <el-select v-model="addFormData.sex" placeholder="选择性别">
            <el-option v-for="item in sexOpions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="personalPhone" label="个人电话">
          <el-input v-model="addFormData.personalPhone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="officialPhone" label="办公电话">
          <el-input v-model="addFormData.officialPhone" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="addFormData.level === 2" prop="departmentId" label="办学单位">
          <el-select filterable v-model="addFormData.departmentId" placeholder="选择办学单位">
            <el-option v-for="item in DepartmentData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>

    <!-- 权限树 -->
    <el-dialog destroy-on-close v-model="treeDialogVisible" title="分配权限" @closed="AuthorityData = []" width="50%">
      <el-tree
        check-on-click-node
        ref="treeRef"
        node-key="id"
        highlight-current
        :default-checked-keys="defaultCheckedKeys"
        :default-expanded-keys="expandedKeys"
        :props="props"
        :data="AuthorityData"
        show-checkbox
        @check="handleCheckChange"
      />
      <template #footer>
        <el-button @click="treeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmTree">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog @closed="sendFormRef?.resetFields()" v-model="sending" title="发送消息" width="500">
      <div>
        <el-form ref="sendFormRef" label-width="80" :model="sendParams">
          <el-form-item label="消息类型" prop="priority">
            <el-select v-model="sendParams.priority" placeholder="Select" size="large" style="width: 240px">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="消息内容" prop="content" :rules="[{ required: true }]">
            <el-input
              autosize
              show-word-limit
              maxlength="255"
              v-model="sendParams.content"
              type="textarea"
              placeholder=""
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="sending = false">取消</el-button>
          <el-button :loading="loading" type="primary" @click="confirmSendMsg"> 发送 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
